package com.qijian.maindata.domain;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.qijian.common.annotation.Excel;
import com.qijian.common.constant.SymbolConstants;
import com.qijian.common.core.domain.BaseEntity;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.StringUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.lang3.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】对象 main_ledger_area_detail
 *
 * @author qijian
 * @date 2024-02-01
 */
@EqualsAndHashCode(callSuper = true)
@Data
@ToString
@TableName("main_ledger_area_detail")
public class LedgerAreaDetail extends BaseEntity {
    private static final long serialVersionUID = 1L;

    @JsonSerialize(using = ToStringSerializer.class)
    @ApiModelProperty(value = "id")
    private Long id;

    @Excel(name = "设备台账id")
    @JsonSerialize(using = ToStringSerializer.class)
    @ApiModelProperty(value = "设备台账id")
    private Long mainId;

    @Excel(name = "区域id")
    @JsonSerialize(using = ToStringSerializer.class)
    @ApiModelProperty(value = "区域id")
    private Long areaId;

    @Excel(name = "区域")
    @ApiModelProperty(value = "区域")
    private String area;

    @ApiModelProperty(value = "type")
    private String type;

    @ApiModelProperty(value = "区域上级")
    private String locationParent;

    @ApiModelProperty(value = "区域上级Id")
    private Long locationParentId;

    /**
     * 根据台账明细拼装区域
     *
     * @param detailList 台账明细
     * @return 区域
     */
    public static String getLocation(List<LedgerAreaDetail> detailList) {
        Map<String, List<String>> locationMap = buildLocationMap(detailList);
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, List<String>> entry : locationMap.entrySet()) {
            String key = entry.getKey();
            List<String> value = entry.getValue();
            if (stringBuilder.length() > 0) {
                stringBuilder.append(SymbolConstants.SEMICOLON);
            }
            stringBuilder.append(key + SymbolConstants.SLASH + SymbolConstants.LEFT_PARENTHESIS + StringUtils.join(value, SymbolConstants.COMMA) + SymbolConstants.RIGHT_PARENTHESIS);
        }
        return stringBuilder.toString();
    }

    /**
     * 根据台账明细拼装区域Map
     *
     * @param detailList 台账明细
     * @return 区域Map
     */
    public static Map<String, List<String>> buildLocationMap(List<LedgerAreaDetail> detailList) {
        Map<String, List<String>> locationMap = new HashMap<>();
        for (LedgerAreaDetail detail : detailList) {
            List<String> locationList = locationMap.get(detail.getLocationParent());
            if (CollUtil.isEmpty(locationList)) {
                locationList = CollUtil.newArrayList(detail.getArea());
            } else {
                locationList.add(detail.getArea());
            }
            locationMap.put(detail.getLocationParent(), locationList);
        }
        return locationMap;
    }

    /**
     * 根据台账明细拼装区域嵌套（前端树展示用）
     *
     * @param detailList 台账明细
     * @return 区域嵌套
     */
    public static List<List<String>> getLocationList(List<LedgerAreaDetail> detailList) {
        List<List<String>> result = CollUtil.newArrayList();
        for (LedgerAreaDetail detail : detailList) {
            result.add(CollUtil.newArrayList(detail.getLocationParent(), detail.getArea()));
        }
        return result;
    }




    /**
     * excel导入时从区域拆分明细
     *
     * @param classifyList
     * @param location      区域
     * @param mainId
     * @param factoryAreaId 厂区id
     * @param factoryArea   厂区
     * @param type          类型
     * @return
     */
    public static List<LedgerAreaDetail> getDetailsFromLocation(List<CommonClassify> classifyList, String location, Long mainId, Long factoryAreaId, String factoryArea, String type) {
        List<LedgerAreaDetail> ledgerAreaDetailList = CollUtil.newArrayList();
        String[] locations = location.split(SymbolConstants.SEMICOLON);
        for (String local : locations) {

            // 区域中的父类 例：1-5
            String locationParent = local.substring(0, local.indexOf(SymbolConstants.SLASH)).trim();
            Optional<CommonClassify> locationPrefixClassify = classifyList.stream().filter(item -> Objects.equals(item.getName(), locationParent) && Objects.equals(item.getParentClassifyId(), factoryAreaId)).findFirst();
            if (!locationPrefixClassify.isPresent()) {
                throw new ServiceException(StrUtil.format("{} 区域未维护", locationParent));
            }
            Long locationParentId = locationPrefixClassify.get().getId();

            Map<String, Long> areaMap = classifyList.stream().filter(item -> Objects.equals(item.getParentClassifyId(), locationParentId)).collect(Collectors.toMap(CommonClassify::getName, CommonClassify::getId));
            String[] split = StringUtils.substringBetween(local, SymbolConstants.LEFT_PARENTHESIS, SymbolConstants.RIGHT_PARENTHESIS).split(SymbolConstants.COMMA);
            for (String s : split) {
                LedgerAreaDetail ledgerAreaDetail = new LedgerAreaDetail();
                ledgerAreaDetail.setMainId(mainId);
                ledgerAreaDetail.setArea(s);
                Long areaId = areaMap.get(s);
                if (ObjectUtils.isEmpty(areaId)) {
                    throw new ServiceException(StrUtil.format("使用厂区为{}没有区域{}", factoryArea, s));
                }
                ledgerAreaDetail.setAreaId(areaId);
                ledgerAreaDetail.setLocationParent(locationParent);
                ledgerAreaDetail.setLocationParentId(locationParentId);
                ledgerAreaDetail.setType(type);
                ledgerAreaDetailList.add(ledgerAreaDetail);
            }
        }
        return ledgerAreaDetailList;
    }


}
